<template>
  <div class="app-container">
    <div class="top-bar-container">
      <el-row>
        <div class="search-container">
          <search-form @search-submit="getMaterialList">
            <search-input v-model="listQuery.name" placeholder="物料名称" />
            <search-select-dict v-model="listQuery.materialType" :dict="materialTypeList" placeholder="物料类型" />
          </search-form>
        </div>
      </el-row>
    </div>

    <el-table :ref="multiple? 'multipleTable' : 'singleTable'" v-loading="listLoading" :data="list" border fit stripe highlight-current-row @current-change="handleCurrentChange">
      <el-table-column
        v-if="multiple"
        type="selection"
        width="55"
      />

      <el-table-column align="center" label="ID" prop="id" width="50" />

      <el-table-column align="center" label="物料名称" prop="name" />

      <el-table-column align="center" label="物料描述" prop="description" />

      <el-table-column align="center" label="物料类型" prop="materialType">
        <template slot-scope="scope">{{ scope.row.materialType | materialTypeFilter }}</template>
      </el-table-column>

      <el-table-column align="center" label="物料内容" prop="materialContent">
        <template slot-scope="scope">
          <el-image v-if="scope.row.materialType === 20" :src="scope.row.materialUrl" :preview-src-list="[scope.row.materialUrl]" />
          <span v-else>{{ scope.row.materialContent | strippedContent }}</span>
        </template>
      </el-table-column>

      <el-table-column v-if="isMaterialTag && materialTagList.length" align="center" label="物料标签">
        <template slot-scope="scope">
          <div class="tag-list">
            <el-tag
              v-for="item in scope.row.tagList"
              :key="item"
              type="success"
            >
              {{ getMaterialTag(item) }}
            </el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="是否绑定" prop="isBound">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isBound? 'success' : 'danger'">{{ scope.row.isBound ? '已绑定' : '未绑定' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        v-if="!multiple"
        align="center"
        fixed="right"
        label="操作"
        width="130"
      >
        <template slot-scope="scope">
          <el-button-group>
            <el-button v-if="scope.row.isBound" type="danger" size="mini" title="解绑" @click="handleDelete(scope.row)">解绑</el-button>
            <el-button v-else type="primary" size="mini" title="选择" @click="handleCurrentChange(scope.row)">选择</el-button>
          </el-button-group>
        </template>
      </el-table-column>

    </el-table>

    <el-form
      ref="editForm"
      :model="editForm"
      :rules="editRules"
      class="edit-form"
      autocomplete="on"
      label-position="right"
      label-width="120px"
    >
      <el-form-item v-if="materialTagList.length > 0" prop="materialTag" label="物料标签">
        <el-select v-model="editForm.materialTag" placeholder="请选择">
          <el-option
            v-for="item in materialTagList"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getMaterialList"
    />

    <div class="footer">
      <el-button @click="$emit('click-close')">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import SearchForm from '@/components/SearchForm'
import SearchInput from '@/components/SearchForm/SearchInput'
import SearchSelectDict from '@/components/SearchForm/SearchSelectDict'
import { searchMaterialList } from '@/api/rest/material'
import { enableStatusList, materialTypeList } from '@/utils/dict'
import { elRequiredRule } from '@/utils/el-validator'

const initForm = {
  selectedList: null,
  materialTag: null
}

export default {
  name: 'InMaterialList',
  components: { SearchInput, Pagination, SearchForm, SearchSelectDict },
  filters: {
    materialTypeFilter(value) {
      const placeType = materialTypeList.find(item => item.value === value)
      return placeType ? placeType.name : ''
    },
    strippedContent: function(string) {
      const newStr = string.replace(/<\/?[^>]+>/ig, '').replace(/[ ]|[&nbsp;]|[&ldquo]/ig, '')
      if (newStr.length > 58) {
        return newStr.substring(0, 58) + '...'
      } else {
        return newStr
      }
    }
  },
  props: {
    multiple: {
      type: Boolean,
      default: false
    },
    selectedList: {
      type: Array,
      default() {
        return []
      }
    },
    isMaterialTag: {
      type: Boolean,
      default: false
    },
    placeKey: {
      type: String,
      default: ''
    },
    materialTagList: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        id: null,
        name: null,
        materialType: null,
        status: 1,
        page: 1,
        limit: 10
      },
      enableStatusList: enableStatusList,
      materialTypeList: materialTypeList,
      currentSelected: null,
      editForm: { ...initForm },
      editRules: {
        materialTag: elRequiredRule
      },
      materialTagMap: {}
    }
  },
  computed: {},
  watch: {
    selectedList(val) {
      this.getMaterialList()
    },
    materialTagList: {
      handler(val, oldVal) {
        this.initMaterialTagMap()
      },
      deep: true
    }
  },
  created() {
    this.initMaterialTagMap()
    this.getMaterialList()
  },
  methods: {
    getMaterialList() {
      this.listLoading = true
      searchMaterialList(this.listQuery).then(response => {
        this.list = []
        // 把已绑定的放在表格最上方
        this.selectedList.forEach(it => {
          this.list.push(Object.assign(it, { isBound: true, tagList: it.tagList }))
        })
        response.data.items.forEach(item => {
          const selected = this.selectedList.find(i => item.id === i.id)
          if (!selected) {
            this.list.push(Object.assign(item, { isBound: false, tagList: [] }))
          }
        })
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleDelete(row) {
      this.$emit('cancel', row.id)
    },
    handleSubmit() {
      if (this.multiple) {
        this.editForm.selectedList = this.$refs.multipleTable.selection
      }

      if (this.editForm.selectedList < 1) {
        this.$alert('请选择物料')
        return false
      }

      if (this.isMaterialTag) {
        this.$refs.editForm.validate(valid => {
          if (valid) {
            this.$emit('selected-list', this.editForm.materialTag, this.editForm.selectedList)
          }
        })
      } else if (this.placeKey != null && this.materialRelTag[this.placeKey]) {
        this.$emit('selected-list', this.editForm.materialTag ?? 'DEFAULT', this.editForm.selectedList)
      } else {
        this.$emit('selected-list', 'DEFAULT', this.editForm.selectedList)
      }
    },
    setCurrent(row) {
      if (this.$refs.singleTable !== null) {
        this.$refs.singleTable.setCurrentRow(row)
      }
    },
    handleCurrentChange(row) {
      this.setCurrent(row)
      this.editForm.selectedList = [row]
    },
    getMaterialTag(type) {
      return this.materialTagMap[type]
    },
    initMaterialTagMap() {
      const map = {}

      this.materialTagList.forEach(item => {
        if (item.name) {
          map[item.value] = item.name
        }
      })

      this.materialTagMap = map
    }
  }
}
</script>
<style scoped>
.footer {
  display: flex;
  justify-content: flex-end;
}
.edit-form {
  margin-top: 20px;
}
>>> .el-table__body tr.current-row > td {
  background-color: #e6fcda !important;
}
>>> .el-table--striped .el-table__body tr.el-table__row--striped.current-row td {
  background-color: #e6fcda !important;
}
.tag-list {
  display: flex;
  flex-direction: column;
}
</style>

